<template>
  <div class="trackingpool-custom">
    <header>
      <span>定制跟踪池</span
      ><atom-icon name="close" class="close" @click.stop="onCloseClick" />
    </header>
    <div class="body">
      <div class="block">
        <div class="title-wrap"><span class="title">仓位管理</span></div>
        <div class="contents">
          <StepperInput
            title="单日最大持股数"
            :min="1"
            :max="limitData.dayBuyLimit"
            :canInput="false"
            v-model="formData.dayBuyLimit"
          />
          <StepperInput
            title="单周最大持股数"
            :min="1"
            :max="limitData.weekBuyLimit"
            :canInput="false"
            v-model="formData.weekBuyLimit"
          />
          <StepperInput
            title="账户最大持股数"
            :min="1"
            :max="limitData.accountBuyLimit"
            v-model="formData.accountBuyLimit"
          />
          <PopupInput
            title="优先买入方式"
            :options="limitData.sortStrateyList"
            @show="$emit('show')"
            @hidden="$emit('hidden')"
            v-model="formData.sortStrateyId"
          />
        </div>
      </div>
      <div class="block">
        <div class="title-wrap">
          <span class="title">更多默认条件</span
          ><span class="sub-title">（默认条件暂不支持修改）</span>
        </div>

        <div class="contents">
          <DefaultBlock
            v-for="{ title, values } in defaultBlcok"
            :key="title"
            :title="title"
            :blockItems="values"
          />
        </div>
      </div>
    </div>
    <div class="button-wrap">
      <div class="button" @click.stop="confirm"><span>确定</span></div>
    </div>
  </div>
</template>

<script>
import StepperInput from '@/components/detail/trackingPoolCustom/StepperInput.vue';
import PopupInput from '@/components/detail/trackingPoolCustom/PopupInput.vue';
import DefaultBlock from '@/components/detail/trackingPoolCustom/DefaultBlock.vue';
import { reqTraceGpcCondition, setTraceGpc } from '@/apis/pool.api';
import '@atom/atom-icons/icons/close';
export default {
  components: {
    StepperInput,
    PopupInput,
    DefaultBlock,
  },
  props: {
    trackingPoolCustomData: {
      type: Object,
      default: () => ({ dayBuyLimit: 1, weekBuyLimit: 1, accountBuyLimit: 1, sortStrateyId: 0 }),
    },
    strategys: {
      type: Object,
      default: () => ({}),
    },
    needSub: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      limitData: {
        dayBuyLimit: 1,
        weekBuyLimit: 1,
        accountBuyLimit: 1,
        sortStrateyList: [],
      },
      formData: {
        dayBuyLimit: 1,
        weekBuyLimit: 1,
        accountBuyLimit: 1,
        sortStrateyId: 0,
      },
      // 默认条件
      defaultBlcok: [],
    };
  },
  methods: {
    // 点击关闭设置订阅池弹窗
    onCloseClick() {
      this.$emit('closePopup');
      this.formData = JSON.parse(JSON.stringify(this.trackingPoolCustomData));
    },
    async getTraceGpcCondition() {
      try {
        const {
          status_code,
          data: { day_buy_limit, week_buy_limit, account_buy_limit, sort_strategy_list },
        } = await reqTraceGpcCondition({ gpc_id: window.getParam('gpc_id') });
        if (status_code) {
          throw new Error(`trackingPoolCustom的index.vue组件的reqTraceGpcCondition接口status_code异常:${status_code}`);
        }
        this.limitData = {
          dayBuyLimit: day_buy_limit,
          weekBuyLimit: week_buy_limit,
          accountBuyLimit: account_buy_limit,
          sortStrateyList: sort_strategy_list,
        };
      } catch (error) {
        _t.errorReport({...error});
      }
    },
    isValid() {
      const isBetween = (num, upper) => num >= 1 && num <= upper;
      const isValidDay = () => isBetween(this.formData.dayBuyLimit, this.limitData.dayBuyLimit);
      const isValidWeek = () => isBetween(this.formData.weekBuyLimit, this.limitData.weekBuyLimit);
      const isValidAccount = () =>
        isBetween(this.formData.accountBuyLimit, this.limitData.accountBuyLimit);
      const isValidsortStratey = () =>
        this.limitData.sortStrateyList.find(item => item.id === this.formData.sortStrateyId);
      return isValidDay() && isValidWeek() && isValidAccount() && isValidsortStratey();
    },
    async confirm() {
      try {
        // 验证数据是否有误
      if (!this.isValid()) {
        this.$toast('数据异常，请检查输入是否正确！');
        throw new Error('跟踪池弹框输入数据异常');
      }
      // 发送修改之后的数据
      const res = await setTraceGpc({
        gpc_id: window.getParam('gpc_id'),
        day_buy_limit: this.formData.dayBuyLimit,
        week_buy_limit: this.formData.weekBuyLimit,
        account_buy_limit: this.formData.accountBuyLimit,
        sort_strategy: this.formData.sortStrateyId,
      });

      if (res.status_code) {
        this.$toast('数据异常，请稍后重试！');
        throw new Error(`trackingPoolCustom的index.vue组件的setTraceGpc接口status_code异常:${res.status_code}`);
      }
      this.$toast('定制成功！');
      // 成功之后关闭弹框
      this.$emit('closePopup');
      // 打开订阅弹框
      if (this.needSub) {
        this.$emit('openSubPopup');
      }
      // 触发事件通知父组件重新调用接口
      this.$emit('updateTrackPoolData');
      } catch (error) {
        _t.errorReport({...error});
      }
    },
    getStrategy(strategy) {
      return strategy?.name ? [strategy.name] : [];
    },
  },
  mounted() {
    this.getTraceGpcCondition();
  },
  watch: {
    trackingPoolCustomData: {
      handler(nval) {
        this.formData = JSON.parse(JSON.stringify(nval));
      },
      immediate: true,
    },
    strategys: {
      handler(nval) {
        const {
          risk_strategy,
          pick_strategy,
          buy_strategy,
          sell_strategy,
          stop_profit_strategy,
          stop_loss_strategy,
        } = nval;
        this.defaultBlcok = [
          {
            title: '风控策略',
            values: this.getStrategy(risk_strategy),
          },
          {
            title: '选股策略',
            values: this.getStrategy(pick_strategy),
          },
          {
            title: '买入策略',
            values: this.getStrategy(buy_strategy),
          },
          {
            title: '卖出策略',
            values: this.getStrategy(sell_strategy),
          },
          {
            title: '止盈策略',
            values: this.getStrategy(stop_profit_strategy),
          },
          {
            title: '止损策略',
            values: this.getStrategy(stop_loss_strategy),
          },
        ];
      },
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
[data-adapter='thsIphoneXAdapter'] {
  .button-wrap {
    padding-bottom: 42px !important;
  }
}

.trackingpool-custom {
  display: flex;
  height: 100%;
  flex-direction: column;
  position: relative;
  background-color: var(--bg-color-2);
  header {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 64px;
    background-color: var(--bg-color-2);
    flex-shrink: 0;
    span {
      font-family: PingFangSC-Medium;
      font-size: 18px;
      color: var(--text-1);
      text-align: center;
      line-height: 22px;
      font-weight: 500;
    }
    .close {
      position: absolute;
      width: 18px;
      height: 18px;
      right: 21px;
      color: var(--text-1);
    }
  }
  .body {
    box-sizing: border-box;
    padding: 8px 16px;
    flex-grow: 1;
    overflow-y: scroll;
    margin-bottom: 76px;

    .block {
      &:not(:first-child) {
        margin-top: 20px;
      }
      .title-wrap {
        margin-bottom: 2px;
        font-size: 16px;

        .title {
          position: relative;
          width: fit-content;
          font-family: PingFangSC-Semibold;
          font-size: 16px;
          color: var(--text-1);
          line-height: 16px;
          font-weight: 600;

          &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 6px;
            opacity: 0.2;
            background-image: linear-gradient(
              270deg,
              rgba(255, 74, 102, 0) 0%,
              rgba(255, 36, 54, 0.6) 100%
            );
            border-radius: 1px;
          }
        }
        .sub-title {
          font-family: PingFangSC-Regular;
          font-size: 14px;
          color: var(--text-3);
          line-height: 18px;
          font-weight: 400;
        }
      }
    }
  }
  .button-wrap {
    position: fixed;
    width: 100%;
    bottom: 0;
    height: 44px;
    padding: 8px 16px;
    background-color: var(--bg-color-2);
    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      width: 343px;
      height: 44px;
      background: var(--atom-color-brand-primary);
      border-radius: 4px;
      span {
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #ffffff;
        text-align: center;
        line-height: 20px;
        font-weight: 400;
      }
    }
  }
}
</style>
